const { Add, Update, QueryOne, QueryList_Page, Exec_Count, Exec, ExecGetOne } = require('../db/dbhelper');
var { init, format } = require('../models/setting');
var { formatDateYear, formatDateTime } = require('../libs/common');
var  {resetdata, reshour} = require('../../server_config.json').sys_config;
var _ = require('underscore');
var moment = require('moment');
const logger = require('../libs/log').logger;

//新增
const settingAdd = async function (doc) {
  let data= await Exec(`select * from hzz_settings where name='${doc.name}'`);
  if(!data){
    await Add('hzz_settings', init(doc));
    return {
      code: 0,
      msg:'新增成功'
    }
  }
  return {
    code: 1,
    msg:'已存在此名称的配置，新增失败'
  }
}

//修改
const settingUpdate = async function (doc) {
  let data= await ExecGetOne(`select * from hzz_settings where name='${doc.name}' AND id <> ${doc.id}`);
  if(!data){
    await Update('hzz_settings', format(doc));
    return {
      code: 0,
      msg:'修改成功'
    }
  }
  return {
    code: 1,
    msg:'已存在此名称的配置，修改失败'
  }
}

//查询详情
const settingInfoByName = async function (doc) {
  try {
    logger.info('-----settingInfoByName---,doc',doc)
    if(!doc || !doc.name){
      return {
        code: 1,
        msg: '缺失参数name'
      }
    }
    let data= await  QueryOne('hzz_settings', {name: doc.name});
    if(data){
      data.createtime = formatDateTime(data.createtime);
      data.updatetime = formatDateTime(data.updatetime);
      if(data.name=='热门职业' || data.name=='线下活动'){
        data.datastr = JSON.parse(data.datastr.toString());
      }
    }
    logger.info('-----settingInfoByName---,result',{
      code: 0,
      data: data
    })
    return {
      code: 0,
      data: data
    }
  } catch (error) {
    logger.info('-----settingInfoByName---,error',error)
    return {
      code: 1,
      msg: '请求异常，请联系客服'
    }
  }
}

//列表
const settingList = async function (doc) {
  try {
    if(!doc || !doc.pagenum || !doc.pagesize){
      return {
        code: 1,
        msg: '缺失分页参数pagenum或pagesize'
      }
    }
    let list= await QueryList_Page('hzz_settings',null,null,doc.pagenum,doc.pagesize);
    list = _.map(list, item=>{
      item.createtime = formatDateTime(item.createtime);
      item.updatetime = formatDateTime(item.updatetime);
      return item;
    })
    let total = await Exec_Count('hzz_settings');
    let pagecount = Math.ceil(total/doc.pagesize);
    return {
      code: 0,
      data:{
        list,
        total,
        pagecount
      },
      msg: '获取成功'
    }
  } catch (error) {
    return {
      code: 1,
      msg: '请求异常，请联系客服'
    }
  }
}

function gettime(){
  // 重置时间
  let now = new Date();
  let hour = now.getHours();
  let rdata;
  if(hour<reshour){
    rdata = new Date(moment(new Date()).format('YYYY-MM-DD')+' '+resetdata).getTime() - (new Date().getTime());
  }else{
    let resetDate = now.setDate(now.getDate()+1);
    rdata = new Date(moment(new Date(resetDate)).format('YYYY-MM-DD')+' '+resetdata).getTime() - (new Date().getTime());
  }
  return {
    code: 0,
    data: rdata
  };
}
// 查询是否已配置首页展示活动
async function isactive(){
  let data= await  QueryOne('hzz_settings', {name: '线下活动'});
  if(data && data.datastr && !JSON.parse(data.datastr.toString()).block){
    return true;
  }else{
    return false;
  }
}

async function usercancel(body){
  try {
    let code= body.code;
    if(!code){
      return {
        code:1,
        msg: '注销失败，未传入用户code'
      };
    }
    //await Exec(`DELETE FROM hzz_accessrecords WHERE pcode ='${code}' OR accesscode='${code}'`);
    await Exec(`DELETE FROM hzz_dailyusers WHERE pcode ='${code}' OR tcode='${code}'`);
    //await Exec(`DELETE FROM hzz_immessages WHERE senderId ='${code}' OR receiverId='${code}'`);
    //await Exec(`DELETE FROM hzz_matchhistories WHERE pcode ='${code}' OR visitcode='${code}'`);
    //await Exec(`DELETE FROM hzz_matchsets WHERE pcode ='${code}'`);
    //await Exec(`DELETE FROM hzz_messages WHERE pcode ='${code}'`);
    await Exec(`DELETE FROM hzz_msgsubscribes WHERE pcode ='${code}'`);
    //await Exec(`DELETE FROM hzz_peoplefans WHERE pcode ='${code}' OR fcode='${code}'`);
    //await Exec(`DELETE FROM hzz_persondes WHERE pcode ='${code}'`);
    //await Exec(`DELETE FROM hzz_uinteresteds WHERE pcode ='${code}' OR fcode='${code}'`);
    await Exec(`DELETE FROM hzz_usertokens WHERE pcode ='${code}'`);
    let user = await ExecGetOne(`select * from hzz_peoples where code='${code}'`);
    await Exec(`UPDATE FROM hzz_peoples set level=99,remarks="${user.remarks+ "已注销"}",phone=null,phone_bak='${user.phone}',openid=null WHERE code ='${code}'`);

    return {
      code: 0,
      msg:'注销成功'
    }
  } catch (error) {
    return {
      code: 0,
      msg:'注销成功'
    }
  }
}

module.exports = {
  settingAdd,
  settingUpdate,
  settingInfoByName,
  settingList,
  gettime,
  isactive,
  usercancel
}